package finedev.work.vennue;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import android.os.Bundle;

import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.AsyncFacebookRunner.RequestListener;

public class AsyncFacebookRunner {
	
	Facebook mFb;

    public AsyncFacebookRunner(Facebook fb) {
        this.mFb = fb;
    }
    
	public void request(String graphPath, Bundle parameters,
			RequestListener listener) {
		
		request(graphPath, parameters, "GET", listener, /* state */null);
	}
	
	public void request(final String graphPath, final Bundle parameters,
			final String httpMethod, final RequestListener listener,
			final Object state) {
		new Thread() {
			@Override
			public void run() {
				try {
					String resp = mFb.request(graphPath, parameters, httpMethod);
					listener.onComplete(resp, state);
				} catch (FileNotFoundException e) {
					listener.onFileNotFoundException(e, state);
				} catch (MalformedURLException e) {
					listener.onMalformedURLException(e, state);
				} catch (IOException e) {
					listener.onIOException(e, state);
				}
			}
		}.start();
	}
	
	public static interface RequestListener {

		/**
		 * Called when a request completes with the given response.
		 * 
		 * Executed by a background thread: do not update the UI in this method.
		 */
		public void onComplete(String response, Object state);

		/**
		 * Called when a request has a network or request error.
		 * 
		 * Executed by a background thread: do not update the UI in this method.
		 */
		public void onIOException(IOException e, Object state);

		/**
		 * Called when a request fails because the requested resource is invalid
		 * or does not exist.
		 * 
		 * Executed by a background thread: do not update the UI in this method.
		 */
		public void onFileNotFoundException(FileNotFoundException e,
				Object state);

		/**
		 * Called if an invalid graph path is provided (which may result in a
		 * malformed URL).
		 * 
		 * Executed by a background thread: do not update the UI in this method.
		 */
		public void onMalformedURLException(MalformedURLException e,
				Object state);

		/**
		 * Called when the server-side Facebook method fails.
		 * 
		 * Executed by a background thread: do not update the UI in this method.
		 */
		public void onFacebookError(FacebookError e, Object state);

	}
}
